<template>
  <PageTitle title="AI 助手" />
  <input id="msg" rows="5" placeholder="请输入问题..." v-model="msg"></input>
    <button id="send" @click="sendMsg()" :disabled="isLoading">
      <span v-if="!isLoading">发送</span>
      <span v-else class="loader"></span>
    </button>
    <button id='save' @click="save" :disabled="isLoading" v-if="answer">
      <span v-if="!isLoading">保存</span>
      <span v-else class="loader"></span>
    </button>
    <hr>
    <img src="/public/lodin.gif" alt="" srcset="" v-if="isLoading"  >
    <div class="answer" v-html="answer">
    </div>
    <hr>
    <div>
        <h2>历史问题</h2>
        <div v-for="item in his_help" :key="item">
            <div v-html="item[0]"></div>
            <div v-html="item[1]"></div>
            <hr>
        </div>
    </div>
</template>
<script setup>
import { ref,computed } from 'vue';
import axios from '../AI-axios/index';
import { useinfoStore } from '@/AI-Stores/info'
import PageTitle from '@/AI-components/PageTitle.vue';
const infoStore = useinfoStore()

let msg = ref('')
let answer = ref("")
let isLoading = ref(false)
let his_help = computed(()=>{
    return infoStore.his_help
})
const save = ()=>{
    infoStore.save([msg.value,answer.value],'helper')
}
const sendMsg =() =>{
    isLoading.value = true
    axios.post('https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', {
        "model": "qwen-plus",
        "messages": [
            {
                "role": "system",
                "content": "你是一个ai助手，帮助我回答问题"
            },
            {
                "role": "user",
                "content": msg.value
            }
        ]
    }, 
    )
    .then(res => {
        console.log(res.data);
        answer.value = marked.parse(res.data.choices[0].message.content);
        infoStore.addQuery()
        infoStore.addCost(res.data.usage.total_tokens)
        console.log(token);
    })
    .finally(() => {
        isLoading.value = false
    })
}
</script>
<style scoped>
.loader {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255,255,255,.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

input, button {
  padding: 12px 16px;
  font-size: 16px;
  border-radius: 8px;
  border: 1px solid #ddd;
}

input {
  width: 80%;
  margin-right: 10px;
}

button {
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

.answer {
  margin-top: 20px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f9f9f9;
  line-height: 1.6;
}

hr {
  margin: 20px 0;
  border: 0;
  border-top: 1px solid #eee;
}
</style>